package com.syh.jn.scm.service.impl.supplier.base;

import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.util.validator.ValidationUtils;
import com.alibaba.dubbo.config.annotation.Service;
import com.syh.core.ddd.infrastructure.repository.AggregateRepository;
import com.syh.core.ddd.service.AbstractServiceImpl;
import com.syh.jn.scm.domain.supplier.entity.base.Project;
import com.syh.jn.scm.domain.supplier.repository.base.ProjectRepository;
import com.syh.jn.scm.dto.supplier.base.project.ProjectMto;
import com.syh.jn.scm.dto.supplier.base.project.ProjectSto;
import com.syh.jn.scm.dto.supplier.base.project.ProjectVo;
import com.syh.jn.scm.service.api.supplier.base.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * 运营项目管理
 */
@Service
@Transactional
public class ProjectServiceImpl extends AbstractServiceImpl<ProjectSto, ProjectMto, ProjectVo, Project, Long> implements ProjectService {
  @Autowired
  private ProjectRepository projectRepository;

  @Override
  protected AggregateRepository<Project, Long> getAggregateRepository() {
    return projectRepository;
  }

  /**
   * 启用运营项目
   * @param id
   */
  @Override
  public void enabled(Long id) {
    //根据id获取运营项目并且判空
    Project project = this.judgeNull(id);
    project.enabled();
    projectRepository.updateStatus(project);
  }

  /**
   * 停用运营项目
   * @param id
   */
  @Override
  public void disabled(Long id) {
    //根据id获取运营项目并且判空
    Project project = this.judgeNull(id);
    project.disabled();
    projectRepository.updateStatus(project);
  }

  /**
   * 保存对象
   * @param sto
   * @return
   */
  @Override
  public Long save(ProjectSto sto) {
    ExtAssert.notNull(sto, "保存对象为空");
    ValidationUtils.validate(sto);
    Project project = new Project();
    project.create(sto);
    return projectRepository.add(project);
  }

  /**
   * 修改对象
   * @param mto
   */
  @Override
  public void update(ProjectMto mto) {
    ExtAssert.notNull(mto, "修改对象为空");
    ValidationUtils.validate(mto);

    Project project = this.judgeNull(mto.getId());
    project.modify(mto);
    projectRepository.update(project);
  }

  /**
   * 删除运营项目，并删除其关联商品
   * @param id
   */
  @Override
  public void delete(Long id) {
    //根据id获取运营项目并且判空
    Project project = this.judgeNull(id);
    project.destroy();
    projectRepository.remove(project);
  }

  /**
   * 根据id获取运营项目并且判空
   * @param id
   * @return
   */
  private Project judgeNull(Long id) {
    Project project = projectRepository.getById(id);
    ExtAssert.notNull(project, "对象不存在");
    return project;
  }
}
